<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #box {
            width: 500px;
            height: 500px;
            margin: 0 auto;
            background-color: #A4A4A4;
            position: relative;
        }
    </style>
</head>
<body>
<input id="btn" type="button" value="弹出小球">
<div id="box"></div>
<script>
    var btn = document.getElementById('btn');
    var box = document.getElementById('box');
    var time=null;
    btn.addEventListener('click', function (e) {
        e = e || window.event;
        var x=0,y=0;
        var span = document.createElement('span');
        var r=Math.floor(Math.random()*256);
        var g=Math.floor(Math.random()*256);
        var b=Math.floor(Math.random()*256);
        var bm=Math.floor(Math.random()*50)+30;
        span.style.cssText = "width: "+bm+"px;" +
            "            height: "+bm+"px;" +
            "            border-radius: 50%;" +
            "            background-color: rgb("+r+","+g+","+b+");" +
            "            display:block;" +
            "            position: absolute;" +
            "            top:0" +
            "            left:0";
        var x1=Math.floor(Math.random()*10)+1;
        var y1=Math.floor(Math.random()*10)+1;
        console.log(box.offsetHeight);
        time=setInterval(function () {
            x+=x1;
            y+=y1;
            if (x<=0||x>=(box.offsetWidth-bm-5)){
                x1=-x1;
            }
            if (y<=0||y>=(box.offsetHeight-bm-5)){
                y1=-y1;
            }

            // if (x>(box.offsetWidth-50)){
            //     x=0;
            // }
            // if (y>(box.offsetHeight-50)){
            //     y=0;
            // }

            span.style.top=y+"px";
            span.style.left=x+"px";
            console.log(x,y);
        },60);
        box.appendChild(span);

    })
</script>
</body>
</html>